import logging
from typing import Optional
from fastapi import APIRouter, Depends, Query, Path
from pydantic import BaseModel, Field
from sqlalchemy import text, inspection
from sqlalchemy.engine import create
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session

from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

data_inspection_router = APIRouter(prefix="/type", tags=["巡查类型管理"], dependencies=[Depends(oauth2_scheme)])


class InspectionSearch(PaginationBase):
    fcheckname: str = Field("", description="类型名称")


@data_inspection_router.get("/list", summary="巡查类型查询接口")
def list_inspection(inspect: InspectionSearch = Query(), db: Session = Depends(get_db)):
    param = {"fcheckname": inspect.fcheckname}
    sql = "select fchecktypeno,fcheckname,fmemo,fupddate,foperator"
    sql = sql + " from s_ts_check_type where 1=1"
    if inspect.fcheckname != "":
        sql = sql + " and fchecktypeno like concat('%', :fcheckname ,'%') "
    count = db.execute(text(sql), param).scalar()

    param = {"fcheckname": inspect.fcheckname}
    sql = "select fchecktypeno,fcheckname,fmemo,fupddate,foperator"
    sql = sql + " from s_ts_check_type where 1=1"
    if inspect.fcheckname != "":
        sql = sql + " and fchecktypeno like concat('%', :fcheckname ,'%') "
    sql = sql + " limit :limit offset :offset "
    param["limit"] = inspect.limit
    param["offset"] = inspect.offset
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fchecktypeno'] = data[key][0]
        d1['fcheckname'] = data[key][1]
        d1['fmemo'] = data[key][2]
        d1['fupddate'] = data[key][3]
        d1['foperator'] = data[key][4]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": inspect.limit, "page": inspect.pageIndex,
                 "pages": (count + inspect.limit - 1) // inspect.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)
